package com.example.myapplicationktkt2.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.example.myapplicationktkt2.R
import com.example.myapplicationktkt2.model.AppInfo

/**
 * 应用列表适配器
 * 用于在ListView中显示应用程序信息
 *
 * @param context 上下文
 * @param appList 应用信息列表
 */
class AppListAdapter(private val context: Context, private val appList: List<AppInfo>) : BaseAdapter() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int {
        return appList.size
    }

    override fun getItem(position: Int): Any {
        return appList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View
        val viewHolder: ViewHolder

        if (convertView == null) {
            view = inflater.inflate(R.layout.item_app, parent, false)
            viewHolder = ViewHolder()
            viewHolder.icon = view.findViewById(R.id.appIcon)
            viewHolder.name = view.findViewById(R.id.appName)
            viewHolder.packageName = view.findViewById(R.id.appPackageName)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        val appInfo = appList[position]
        viewHolder.icon?.setImageDrawable(appInfo.icon)
        viewHolder.name?.text = appInfo.name
        viewHolder.packageName?.text = appInfo.packageName

        return view
    }

    /**
     * ViewHolder模式优化ListView性能
     */
    private class ViewHolder {
        var icon: ImageView? = null
        var name: TextView? = null
        var packageName: TextView? = null
    }
}